﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Company;
using NHibernate;
using Broker.View.ViewModel;
using Broker.View.ProductView;
using BrokerBase.Lib.Product;

namespace Broker.View.DemoView
{
    /// <summary>
    /// ProductPage.xaml 的交互逻辑
    /// </summary>
    public partial class ProductBrowserPage 
    {
        private IEnumerable<ICompany> companies;

        public ProductBrowserPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(ProductPage_Loaded);
        }

        void ProductPage_Loaded(object sender, RoutedEventArgs e)
        {
            //ISession sess=LibGlobal.HbmSessionFactory.OpenSession();

            //companies = sess.CreateQuery("select p.Company from Product p where p.Name like '%生命%' group by p.Company" ).Enumerable<ICompany>();

            //tvProduct.ItemsSource = companies;
            LoadProduct(null);
            
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            LoadProduct(txtSearch.Text.Trim());
        }


        private void LoadProduct(string likeName)
        {
            IList<ProductNameModel> products = ProductNameModel.LoadByLikeName(likeName);

            IEnumerable<IGrouping<string, ProductNameModel>> result = products.GroupBy(p => p.CompanyName);

            IList<CompanyNameModel> companies = new List<CompanyNameModel>();

            foreach (IGrouping<string, ProductNameModel> r in result)
            {
                CompanyNameModel cnm = new CompanyNameModel();
                cnm.Name = r.Key;
                cnm.Products = r;

                companies.Add(cnm);
            }

            tvProduct.ItemsSource = companies;
            tbkSum.Text = products.Count() + "个产品";
        }

        private void tvProduct_Selected(object sender, Telerik.Windows.RadRoutedEventArgs e)
        {
            if (tvProduct.SelectedItem != null && tvProduct.SelectedItem is ProductNameModel)
            {
                ProductNameModel p = tvProduct.SelectedItem as ProductNameModel;

                ISession sess = LibGlobal.HbmSessionFactory.GetCurrentSession();
                IProduct product = sess.Load<Product>(p.Id);
                ProductPage page = new ProductPage(product,LibGlobal.MainWindow);

                fmProduct.Content = page;
            }
        }
    }
}
